import axios from 'axios'
import store from '@/store'
import { VueAxios } from './axios'
import MessageUtil from './MessageUtil'
import LocaleUtil from "./LocaleUtil";
import {Modal} from 'ant-design-vue'
import TokenStorageUtil from "./TokenStorageUtil";

/**
 * 【指定 axios的 baseURL】
 * 如果手工指定 baseURL: '/yuncheng-boot'
 * 则映射后端域名，通过 vue.config.js
 * @type {*|string}
 */
let apiBaseUrl = bootConfig[process.env.NODE_ENV].VUE_APP_API;
//console.log("apiBaseUrl= ",apiBaseUrl)
// 创建 axios 实例
const service = axios.create({
  //baseURL: '/yuncheng-boot',
  baseURL: apiBaseUrl, // api base_url
  timeout: 60000 // 请求超时时间
})

const err = (error) => {
  if (error.response) {
    let data = error.response.data
    const token = TokenStorageUtil.get()
    switch (error.response.status) {
      case 403:
        MessageUtil.error(LocaleUtil.getLocale('m.common.tip.access_denied'), LocaleUtil.getLocale('m.common.tip.system_prompt'))
        break
      case 500:
        break
      case 404:
        MessageUtil.error(LocaleUtil.getLocale('m.common.tip.resource_not_found'),LocaleUtil.getLocale('m.common.tip.system_prompt'))
        break
      case 504:
        MessageUtil.error(LocaleUtil.getLocale('m.common.tip.network_timeout'), LocaleUtil.getLocale('m.common.tip.system_prompt'))
        break
      case 401:
        if (token) {
          setTimeout(function () {
            const tokenAfterTime = TokenStorageUtil.get()
            if (!tokenAfterTime) {
              return
            }
            Modal.error({
              title: LocaleUtil.getLocale('m.common.tip.token_expired'),
              content: LocaleUtil.getLocale('m.common.tip.token_expired_tip'),
              okText: LocaleUtil.getLocale('m.common.tip.re_login'),
              mask: false,
              onOk: () => {
                store.dispatch('Logout').then(() => {
                  window.location.reload()
                })
              }
            })
          }, 500)
        } else {
          MessageUtil.error(LocaleUtil.getLocale('m.common.tip.unauthorized'), LocaleUtil.getLocale('m.common.tip.system_prompt'))
        }
        break
      default:
        MessageUtil.error(data.message, LocaleUtil.getLocale('m.common.tip.system_prompt'))
        break
    }
  }
  return Promise.reject(error)
};

// request interceptor
service.interceptors.request.use(config => {
  // //console.log('config',config) //看接口的API等...
  if(config.url_1 == 'outside'){
    config.baseURL = bootConfig[process.env.NODE_ENV].locality_ApI;
  }
  if(config.url_2 == 'outside'){
    config.baseURL = bootConfig[process.env.NODE_ENV].locality_ApI2;
  }
  const token = TokenStorageUtil.get()
  if (token) {
    config.headers[ 'X-Access-Token' ] = token // 让每个请求携带自定义 token 请根据实际情况自行修改
  }
  if(config.method=='get'){
    if(config.url.indexOf("system/dict/getDictItems")<0){
      config.params = {
        _t: Date.parse(new Date())/1000,
        ...config.params
      }
    }
  }
  // 多语言
  // 如果禁用了切换语言，则不会往后台传递语言变量，后台采用默认语言
  if (bootConfig[process.env.NODE_ENV].VUE_APP_LOCALE_ENABLE) {
    if (config.url && config.url.indexOf("\?") === -1) {
      config.url = config.url + "?lang=" + store.getters.language
    } else if (config.url) {
      config.url = config.url + "&lang=" + store.getters.language
    }
  }
  return config
},(error) => {
  return Promise.reject(error)
})

// response interceptor
service.interceptors.response.use((response) => {

  //console.log(response)
  //console.log(response.data.byteLength)
  //console.log(response.data instanceof ArrayBuffer)
  // //console.log(response)
  if (response.data.byteLength && response.data instanceof ArrayBuffer) {
    const decoder = new TextDecoder('utf-8');
    const decodedData = decoder.decode(response.data) ;
    //console.log(response)
    //console.log(decodedData.indexOf('code'))
    if(response.status !== 200 && decodedData.indexOf('code') !== -1){
      return JSON.parse(decodedData)
    }else{
      //console.log('我返回这个请求1',response.data)
      return response.data
    }
  }else{
    //console.log('我返回这个请求2',response.data)
    return response.data
  }


  }, err)

const installer = {
  vm: {},
  install (Vue, router = {}) {
    Vue.use(VueAxios, router, service)
  }
}

export {
  installer as VueAxios,
  service as axios
}
